import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:group_button/group_button.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/LjgmOrder.dart';
import 'package:shop/shop/life/ServiceIndexPage.dart';

import 'GoodsListPage.dart';
import 'Login.dart';
import 'MerchantListPage.dart';

/**
 * 服务商家列表页面
 */
class ServiceHomePage extends StatefulWidget {
  // final String gid; //商品ID
  ServiceHomePage({Key key}) : super(key: key);

  @override
  _ServiceHomePage createState() => _ServiceHomePage();
}

class _ServiceHomePage extends State<ServiceHomePage> {

  String gName = "";//商品名称
  int page=1;//页数

  // 构造方法
  // _ServiceHomePage() {
  //   _onLoading();
  // }

  List goods=[
    // {"dianpu":"一帘幽梦","shijian":"2021-9-22","xiangmu":"全身精油SPA"},
    // {"dianpu":"一帘幽梦","shijian":"2021-9-22","xiangmu":"泰式按摩"},
    // {"dianpu":"一帘幽梦","shijian":"2021-9-22","xiangmu":"桑拿"},
    ];//商品集合

  List _imageUrls = [
    "http://b1-q.mafengwo.net/s9/M00/A5/88/wKgBs1d2ByKAXc2JAACsSNXA-sA34.jpeg",
    "http://b1-q.mafengwo.net/s9/M00/A3/F0/wKgBs1d2BFyAceutAADiqnHT0ys50.jpeg"
  ]; //定义图片存储的数组
  String guiges = ""; //字符串规格
  String guigexiabiao = ""; //字符串规格下标
  dynamic funCb;
  FocusNode _focusNode = FocusNode(); // 焦点事件

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMerchantType();//得商户类型
    _getServiceMerchant();//得服务型商户
    // 焦点事件处理
    _focusNode.addListener((){
      if (!_focusNode.hasFocus) {
        print('失去焦点');
      }else{
        print('得到焦点');
        MyRoute.push(GoodsListPage(gName: "",sort: 0,type: 0,));
        _focusNode.unfocus();
      }
    });
  }

  //得服务型商户集合
  _getServiceMerchant() async {
    var x = await HttpUtil().get("/waimai/merchant/getfenyeMerchantInfo?limit=10&page=$page&type=1");
    if(x['code']==200){
      goods = x['data'];
    }
    setState(() {

    });
  }

  List merchantTypeList = [];//商户类型集合
  //得服务型商户类型
  _getMerchantType() async {
    var x  = await HttpUtil().get("/waimai/merchantType/searchAllMerchantType?type=1");
    if(x['code']==200){
      merchantTypeList.addAll(x['data']);
    }
    setState(() {});
  }

  @override
  void dispose() {
    _focusNode.unfocus();
    super.dispose();
  }
// 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  void _onRefresh() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
  // 加载数据的函数
  void _onLoading() async{
    print("开始加载");
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/goods/searchAllGoods?limit=10&page=${page}");
    // var x = json.decode(response.toString());
    // var x;
    // if(type==0){
    //   x = await HttpUtil().get("/app/goods/searchAllGoods?limit=10&page=${page}&gName="+gName+"&sort=${sort}");
    // }else{
    //   x = await HttpUtil().get("/app/goodsType/getGoodsTypeAllGoods?limit=10&page=${page}&id=${typeId}&gName="+gName);
    // }
    // page++;
    // if(x['code']==200){
    //   goods.addAll(x['data']);
    // }
    // if(x['data'].length<1){
    //   _refreshController.loadNoData();
    //   return;
    // }
    // // if failed,use loadFailed(),if no data return,use LoadNodata()
    // if(mounted){
    //   setState(() {});
    //   _refreshController.loadComplete();
    // }
    _refreshController.loadNoData();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
       backgroundColor: Colors.white,
       elevation: 0,
       title:Container(
        color: Colors.white,
        child: Row(children: [
          // Icon(Icons.search,color: Colors.orange,),
          Expanded(child: Container(
            width: ScreenUtil().setWidth(430),
            height: ScreenUtil().setHeight(45),
            margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(20)),
              border: Border.all(color: Colors.orange , width: 1),
            ),
            child: Row(
              children: [
                Expanded(child: Container(
                  child: TextField(
                    focusNode: _focusNode,
                    decoration: InputDecoration(
                      hintText: "搜索店家、服务名",
                      contentPadding: EdgeInsets.fromLTRB(15, 0, 0, 6),
                      border: InputBorder.none,
                    ),
                    onChanged: (text){
                      gName = text;
                    },
                  ),
                )),
                Container(
                  padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
                  child: Icon(Icons.search,color: Colors.orange,),
                )
              ],
            ),
            // child: TextField(
            //   focusNode: _focusNode,
            //   decoration: InputDecoration(
            //     hintText: "搜索店家、服务名",
            //     contentPadding: EdgeInsets.fromLTRB(15, 0, 0, 6),
            //     border: InputBorder.none,
            //   ),
            //   onChanged: (text){
            //     gName = text;
            //   },
            // ),
          )),
        ],),
      )),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
            child:Container(
              margin: EdgeInsets.fromLTRB(0, 16, 0, 6),
              decoration: BoxDecoration(
                color: Colors.white,
              ),
              child: Wrap(
                direction: Axis.horizontal,
                spacing: 20,
                runSpacing: 10,
                alignment: WrapAlignment.spaceAround,
                children:
                  _buildMerchantType()
                  // GestureDetector(
                  //   child: Column(
                  //     children: [
                  //       CachedNetworkImage(imageUrl: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F014f855c9882dda8012141683d3f2a.jpg%402o.jpg",height: 60,fit: BoxFit.fitHeight,),
                  //       Text("SPA"),
                  //     ],
                  //   ),
                  //   onTap: (){
                  //
                  //   },
                  // ), GestureDetector(
                  //   child: Column(
                  //     children: [
                  //       CachedNetworkImage(imageUrl: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ftm-image.qccip.com%2FqcctmImage%2F9bf337bbae42ace05cdb28368468577e.jpg",height: 60,fit: BoxFit.fitHeight,),
                  //       Text("桑拿"),
                  //     ],
                  //   ),
                  //   onTap: (){
                  //
                  //   },
                  // ),
                  // GestureDetector(
                  //   child: Column(
                  //     children: [
                  //       CachedNetworkImage(imageUrl: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ftm-image.qccip.com%2FqcctmImage%2F9bf337bbae42ace05cdb28368468577e.jpg",height: 60,fit: BoxFit.fitHeight,),
                  //       Text("足浴"),
                  //     ],
                  //   ),
                  //   onTap: (){
                  //
                  //   },
                  // ),
              )
            )),
            SliverList(delegate: SliverChildBuilderDelegate((content,index){
              return GestureDetector(
                child: Container(
                  decoration: BoxDecoration(color: Colors.white,border: Border(bottom: BorderSide(width: 1,color: Colors.blue)) ,),
                  padding: EdgeInsets.symmetric(vertical: 10,horizontal: 10),
                  child: Row(
                    children: [
                      CachedNetworkImage(imageUrl: Config.getInstance().getHost()+goods[index]['picture'],width: ScreenUtil().setWidth(100),height: ScreenUtil().setHeight(100),),
                      Container(
                        width: ScreenUtil().setWidth(330),
                        height: ScreenUtil().setHeight(100),
                        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(child: Text(goods[index]['mname'], maxLines:1, style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22,color: Colors.red),),) ,
                            Container(child:Row(
                              children: [
                                Expanded(child: Text(goods[index]['jianjie'],maxLines: 1,)) ,
                                GestureDetector(child: Container(
                                  padding: EdgeInsets.all(5),
                                  decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.all(Radius.circular(5)) ,),
                                  child: Text("预约",style: TextStyle(color: Colors.white),),
                                ),)
                              ],
                            ),)
                          ],
                        ),
                      )
                      // Container(child: Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Expanded(child: Text(goods[index]['mname'], maxLines:1, style: TextStyle(fontWeight: FontWeight.bold,fontSize: 22,color: Colors.red),),) ,
                      //   ],
                      // ),),
                      // // SizedBox(width: 10,),
                      // Container(child: Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Expanded(child: Text(goods[index]['jianjie'],maxLines: 1,)) ,
                      //     GestureDetector(child: Container(
                      //       padding: EdgeInsets.all(5),
                      //       decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.all(Radius.circular(5)) ,),
                      //       child: Text("预约",style: TextStyle(color: Colors.white),),
                      //     ),
                      //     )
                      //   ],
                      // ),)
                    ],
                  ),
                ),
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  List<String> mTypeIdList = goods[index]['mType'].toString().split(",");
                  MyRoute.push(ServiceIndexPage(mId: goods[index]['id'],merchantTypeId: mTypeIdList[0],));
                },
              );
            },childCount: goods.length))
          ],
        )
      ),
    );
  }

  // 显示店铺类型
  _buildMerchantType() {
    List<Widget> x = [];
    for(int i=0;i<merchantTypeList.length;i++){
      x.add(GestureDetector(
        child: Column(
          children: [
            Container(
              height: ScreenUtil().setHeight(60),
              width: ScreenUtil().setWidth(60),
              decoration: BoxDecoration(
                borderRadius:BorderRadius.circular(10),
                image: new DecorationImage(
                  image: new NetworkImage(Config.getInstance().getHost()+merchantTypeList[i]['picture']),
                )
              ),
            ),
            Text(merchantTypeList[i]['name'],style:TextStyle(
                decoration: TextDecoration.none
            ))
          ],
        ),
        onTap: (){
          print("商户类型："+merchantTypeList[i]['id']);
          MyRoute.push(MerchantListPage(merchantTypeId:merchantTypeList[i]['id']));
        },
      ));
    }
    return x;
  }
}
